using System;
using System.BusinessObjects.Transactions;
using Blazing.BusinessObjects.Tagging;
using NHibernate;
using NHibernate.Criterion;

namespace Blazing.BusinessObjects.Queries
{
    public class QrySearchTaxonomyTagsByParent
    {
        /// <summary>
        /// Search for taxonomytags with a given parent.
        /// </summary>
        /// <param name="parentID">The parent tag's id.</param>
        /// <param name="attachedOnly">Limits the results to those tags that are currently attached to a building.</param>
        /// <returns></returns>
        public static IQuery Query(int parentID, bool attachedOnly)
        {
            string hql;
            string param;
            IQuery qry;
            if (parentID > 0)
                param = ".ID=" + parentID.ToString(); 
            else
                param = " is null";
            if (attachedOnly)
            {
                //hql = string.Format("select distinct t from Building b join b.BuildingTaxonomyTags t where t.ParentTaxonomyTag{0}", param);
                hql = string.Format("select distinct t from TaxonomyTag t where t.ParentTaxonomyTag{0}", param);
            }
            else
            {
                hql = string.Format("select tag from TaxonomyTag tag where tag.ParentTaxonomyTag{0}", param);                
            }
            qry = UnitOfWork.CurrentSession.CreateQuery(hql);
            qry.SetCacheable(true);
            return qry;
        }

        public static IQuery QueryAttachedToBuildings()
        {
            string hql = "select distinct t from Building b join b.BuildingTaxonomyTags t";
            IQuery qry = UnitOfWork.CurrentSession.CreateQuery(hql);
            qry.SetCacheable(true);
            return qry;
        }
    }
}
